package com.goodcol.plugin.ui;

import com.goodcol.plugin.dto.SettingsStorageDTO;
import com.goodcol.plugin.service.SettingsStorageService;
import com.goodcol.plugin.service.impl.ClipboardExportImportSettingsServiceImpl;
import com.goodcol.plugin.service.impl.LocalFileExportImportSettingsServiceImpl;
import com.goodcol.plugin.service.impl.UrlExportImportSettingsServiceImpl;
import com.goodcol.plugin.tool.Constants;
import com.goodcol.plugin.tool.JSON;
import com.goodcol.plugin.tool.LicenseUtils;
import com.goodcol.plugin.tool.MessageDialogUtils;
import com.goodcol.plugin.tool.ProjectUtils;
import com.goodcol.plugin.tool.StringUtils;
import com.goodcol.plugin.ui.component.ExportImportComponent;
import com.goodcol.plugin.ui.component.ListCheckboxComponent;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.ui.DialogBuilder;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.ui.TitledSeparator;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.TextTransferable;
import com.sun.net.httpserver.HttpServer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Objects;

/**
 * @author QuickCode
 * @version 1.0.0
 */

public class MainSettingForm implements Configurable.Composite, BaseSettings {
    private JLabel versionLabel;
    private JButton resetBtn;
    private JButton exportByNetBtn;
    private JButton importByNetBtn;
    private JButton exportByFileBtn;
    private JButton importByFileBtn;
    private JButton exportByClipboardBtn;
    private JButton importByClipboardBtn;
    private JPanel mainPanel;
    private JTextField authorEditor;
    private JLabel authorTitle;
    private JPanel exportTitledSeparatorPanel;
    private JPanel exportItemPanel;
    private JPanel importTitledSeparatorPanel;
    private JButton regBtn;
    private ListCheckboxComponent templateCheckboxPanel;
    private ListCheckboxComponent typeMapperCheckboxPanel;
    private ListCheckboxComponent columnConfigCheckboxPanel;
    private ListCheckboxComponent globalConfigCheckboxPanel;

    /**
     * 子配置
     */
    private Configurable[] childConfigurableArray;

    /**
     * MainSettingForm
     */
    public MainSettingForm() {
        // nothing
    }

    private void initExportImportEvent() {
        new ExportImportComponent(this.exportByFileBtn, this.importByFileBtn, this.templateCheckboxPanel, this.typeMapperCheckboxPanel,
                this.columnConfigCheckboxPanel, this.globalConfigCheckboxPanel,
                new LocalFileExportImportSettingsServiceImpl(), this::loadChildSettingsStore);
        new ExportImportComponent(this.exportByNetBtn, this.importByNetBtn, this.templateCheckboxPanel, this.typeMapperCheckboxPanel,
                this.columnConfigCheckboxPanel, this.globalConfigCheckboxPanel,
                new UrlExportImportSettingsServiceImpl(), this::loadChildSettingsStore);
        new ExportImportComponent(this.exportByClipboardBtn, this.importByClipboardBtn, this.templateCheckboxPanel, this.typeMapperCheckboxPanel,
                this.columnConfigCheckboxPanel, this.globalConfigCheckboxPanel,
                new ClipboardExportImportSettingsServiceImpl(), this::loadChildSettingsStore);
    }

    private void initEvent() {
        this.resetBtn.addActionListener(e -> {
            boolean result = MessageDialogUtils.yesNo("确认恢复默认设置，所有Default分组配置将被重置，并且已删除的默认分组将被还原。确认继续？");
            if (result) {
                // 重置默认值后重新加载配置
                getSettingsStorage().resetDefaultVal();
                this.loadSettingsStore();
                this.loadChildSettingsStore();
            }
        });
        // License注册按钮
        regBtn.addActionListener(e -> {
            // 创建 LicenseDialog 实例
            LicenseDialog licenseDialog = new LicenseDialog(ProjectUtils.getCurrProject());
            // 设置对话框的一些属性，例如大小、位置、是否模态等
            licenseDialog.setSize(450, 200);
            // 显示对话框
            licenseDialog.show();
        });
    }

    @Override
    public String getDisplayName() {
        return "QuickCode";
    }

    @Nullable
    @Override
    public String getHelpTopic() {
        return getDisplayName();
    }

    @Override
    public Configurable @NotNull [] getConfigurables() {
        TemplateSettingForm templateSettingForm = new TemplateSettingForm();
        this.childConfigurableArray = new Configurable[]{
                new TypeMapperSettingForm(),
                templateSettingForm,
                new ColumnConfigSettingForm(),
                new GlobalConfigSettingForm(templateSettingForm),
        };
        this.loadChildSettingsStore();
        return this.childConfigurableArray;
    }

    private void loadChildSettingsStore() {
        // 初始装置配置信息
        for (Configurable configurable : this.childConfigurableArray) {
            if (configurable instanceof BaseSettings) {
                ((BaseSettings) configurable).loadSettingsStore();
            }
        }
    }

    @Override
    public @Nullable JComponent createComponent() {
        // 初始图标
        this.authorTitle.setIcon(AllIcons.Actions.IntentionBulb);
        this.exportTitledSeparatorPanel.add(new TitledSeparator("导出配置（请勾选需要导出的配置）"));
        this.importTitledSeparatorPanel.add(new TitledSeparator("导入配置"));
        // 加载储存数据
        this.loadSettingsStore();
        this.initExportItem();
        // 初始化事件
        this.initEvent();
        this.initExportImportEvent();
        return mainPanel;
    }

    @Override
    public boolean isModified() {
        return !Objects.equals(this.authorEditor.getText(), getSettingsStorage().getAuthor());
    }

    @Override
    public void apply() throws ConfigurationException {
        String author = this.authorEditor.getText();
        if (StringUtils.isEmpty(author)) {
            throw new ConfigurationException("作者名称不能为空");
        }
        getSettingsStorage().setAuthor(author);
    }

    /**
     * 加载配置信息
     *
     * @param settingsStorage 配置信息
     */
    @Override
    public void loadSettingsStore(SettingsStorageDTO settingsStorage) {
        this.versionLabel.setText(Constants.VERSION);
        this.authorEditor.setText(settingsStorage.getAuthor());
    }

    /**
     * 初始化导出项
     */
    private void initExportItem() {
        // 复制一份，避免篡改
        SettingsStorageDTO settingsStorage = SettingsStorageService.getSettingsStorage();
        JPanel panel = new JPanel(new GridLayout(1, 4));
        // Template
        this.templateCheckboxPanel = new ListCheckboxComponent("Template", settingsStorage.getTemplateGroupMap().keySet());
        panel.add(templateCheckboxPanel);
        // Type Mapper
        this.typeMapperCheckboxPanel = new ListCheckboxComponent("Type Mapper", settingsStorage.getTypeMapperGroupMap().keySet());
        panel.add(typeMapperCheckboxPanel);
        // Column Config
        this.columnConfigCheckboxPanel = new ListCheckboxComponent("Column Config", settingsStorage.getColumnConfigGroupMap().keySet());
        panel.add(columnConfigCheckboxPanel);
        // GlobalConfig
        this.globalConfigCheckboxPanel = new ListCheckboxComponent("Global Config", settingsStorage.getGlobalConfigGroupMap().keySet());
        panel.add(globalConfigCheckboxPanel);
        exportItemPanel.add(panel);
    }

}
